package topic;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * TODO
 *
 * @author gaoxiang
 * @date 2021/7/280:06
 */
public class TopicReceive {
    public static void main(String[] args) throws Exception{
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("121.41.192.69");//设置RabbitMQ的主机IP
        factory.setPort(5672);//设置RabbitMQ的端口号
        factory.setUsername("guest");//设置访问用户名
        factory.setPassword("guest");//设置访问密码
        Connection connection = factory.newConnection();
        //8、创建频道-channel = connection.createChannel()
        Channel channel = connection.createChannel();
        //9、声明队列-channel.queueDeclare(名称，是否持久化，是否独占本连接,是否自动删除,附加参数)
        channel.queueDeclare("topic_queue1",true,false,false,null);
        channel.exchangeDeclare("exchange_top", BuiltinExchangeType.TOPIC, true);
        //队列绑定交换机与路由key
        channel.queueBind("topic_queue1", "exchange_top", "log.*.*");

        /**
         * 消息消费
         * 参数1：队列名称
         * 参数2：是否自动应答，true为自动应答[mq接收到回复会删除消息]，设置为false则需要手动应答
         * 参数3：消息接收到后回调
         */
        channel.basicConsume("topic_queue1",true,new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                //获取消息数据
                String bodyStr = new String(body, "UTF-8");
                System.out.println(bodyStr);
            }
        });

    }
}
